﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using giaoxuhaison.Models;
using giaoxuhaison.Common;
using System.Web.Security;
using System.IO;
using giaoxuhaison.MembershipServices;
using System.Data.Entity;
using System.Data;
using System.Text;
using System.Configuration;

namespace giaoxuhaison.Controllers
{
    public class CultureController : Controller
    {
        //
        // GET: /Culture/
        private IBuildGridDataHelper<CultureModels> _gridhelper;
        private IBuildGridDataHelper<CultureModels> _gridhelperNewsAll;
        private bool Initialized = false;
        private gxhaisonEntities conn = new gxhaisonEntities();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult TabCulture()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            ViewData["lstNewCulture"] = GetNewCulture();
            return PartialView();
        }

        public ActionResult CultureGroup(int GroupID, int currentPage = 1)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            var model = GetListGroup(GroupID, currentPage);
            //ViewData["lstCulture"] = GetListGroup(GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return View(model);
        }

        public ActionResult CultureDetail(int CultureID, int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstCulture"] = GetCultureDetail(CultureID);
            ViewData["lstOtherCulture"] = GetOtherCulture(CultureID, GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);

            return PartialView();
        }

        public ActionResult NewCulture()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            ViewData["lstCulture"] = GetNewCulture();
            return PartialView();
        }


        /*--Định nghĩa các hàm lấy dữ liệu*/
        private ResultList GetListGroup(int GroupID, int currentPage = 1)
        {
            var skipNumber = (currentPage - 1) * 6;
            var resultList = new ResultList();
            var repNewsAll = conn.vw_CulturesAll.Where(t => t.Locked == false && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).AsQueryable();

            resultList.CurrentPage = currentPage;
            resultList.TotalRecords = repNewsAll.Count();
            resultList.EntityList = repNewsAll.Skip(skipNumber).Take(6).ToList().Select(t => t as ModelBase).ToList();

            return resultList;            
        }

        private List<vw_CulturesAll> GetCultureDetail(int CultureID)
        {
            var lstItem = conn.vw_CulturesAll.Where(t => t.Locked == false && t.CultureID == CultureID).OrderByDescending(t => t.CreationDate).ToList();
            return lstItem;
        }

        private List<vw_CulturesAll> GetOtherCulture(int CultureID, int GroupID)
        {
            var lstItem = conn.vw_CulturesAll.Where(t => t.Locked == false && t.CultureID != CultureID && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).Take(5).ToList();
            return lstItem;
        }

        private List<vw_CulturesAll> GetNewCulture()
        {
            var lstItem = conn.vw_CulturesAll.Where(t => t.Locked == false).OrderByDescending(t => t.CreationDate).Take(15).ToList();
            return lstItem;
        }
        private List<LinkPath> GetLinkPath(int GroupID)
        {
            var lstItem = conn.LinkPaths.Where(t => t.GroupID == GroupID).ToList();
            return lstItem;
        }
        /*end*/
        /*phan quan tri*/
        public ActionResult ManageCulture()
        {
            if (Request.IsAuthenticated)
            {
                ViewData["lstNewsGrp"] = GetListNewsGrp("");
                ViewData["lstNewsGrpSrch"] = GetListNewsGrp("SEARCH");
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Admin"); ;
            }
        }

        private List<ListGroupModels> GetListNewsGrp(string strCon)
        {
            List<ListGroupModels> lst = new List<ListGroupModels>();
            ListGroupModels item = new ListGroupModels();
            ListGroupModels item1 = new ListGroupModels();
            ListGroupModels item2 = new ListGroupModels();
            ListGroupModels item3 = new ListGroupModels();
            ListGroupModels item4 = new ListGroupModels();

            if (strCon == "SEARCH")
            {
                item4.GroupID = 0;
                item4.GroupName = "Tất cả";
                lst.Add(item4);
            }

            item.GroupID = 13;
            item.GroupName = "Kỹ năng sống";
            lst.Add(item);

            item1.GroupID = 14;
            item1.GroupName = "Truyện - thơ";
            lst.Add(item1);

            return lst;
        }

        private string[] CreateRowsJSonNewsAll(CultureModels model)
        {
            List<string> result = new List<string>();
            string format = "dd-mm-yyyy";
            result.Add(model.CultureID.ToString());
            result.Add(model.GroupID.ToString());
            result.Add(model.GroupName);
            result.Add(model.Subject);
            result.Add(model.ImageContentUrl);
            result.Add(model.ShortcutText);
            result.Add(model.Contents);
            result.Add(model.VisibleContent.ToString());
            result.Add(model.Locked.ToString());
            result.Add(model.CreationDate.ToShortDateString());
            return result.ToArray();

        }

        private void InitHelperNewsAll()
        {
            /*
             * Hungnvv : 03/04/2013
             */

            IEntityHelper entity = new EntityHelper();
            IPageCalculator pageCalc = new PageCalculator();
            ISortBuilder _sortBuilder = new SortBuilder(entity);
            IFilterBuilder _filterBuilder = new FilterBuilder(entity);

            //this._retrieveHandler = new RetrieveHandler(entity);
            this._gridhelperNewsAll = new BuildGridDataHelper<CultureModels>(pageCalc, entity, _sortBuilder, _filterBuilder);

            Initialized = true;

            return;
        }
        public string GetAllNews(int Condition_GroupID, string Condition_Find, string sortName, string sortOrder, int rowNumber, int rowId,
            int page, string searchField, string searchOper, string searchString)
        {
            if (!Initialized) InitHelperNewsAll();

            CultureModels model = new CultureModels();
            model.Condition_GroupID = Condition_GroupID;
            model.Condition_Find = Condition_Find;

            return _gridhelperNewsAll.BuildDataForGrid(GetListNews(model), CreateRowsJSonNewsAll,
              sortName, "desc", rowNumber, rowId, page, searchField, searchOper, searchString);

        }

        private List<CultureModels> GetListNews(CultureModels modelNewsAll)
        {
            var Item = new List<CulturesAll>();

            if (modelNewsAll.Condition_GroupID == 0)
            {
                Item = conn.CulturesAlls.Where(t => (t.Subject.Contains(modelNewsAll.Condition_Find) || t.ShortcutText.Contains(modelNewsAll.Condition_Find) || t.Contents.Contains(modelNewsAll.Condition_Find))).OrderByDescending(t => t.CreationDate).ToList();
            }
            else
            {
                Item = conn.CulturesAlls.Where(t => t.GroupID == modelNewsAll.Condition_GroupID && (t.Subject.Contains(modelNewsAll.Condition_Find) || t.ShortcutText.Contains(modelNewsAll.Condition_Find) || t.Contents.Contains(modelNewsAll.Condition_Find))).OrderByDescending(t => t.CreationDate).ToList();
            }
            List<CultureModels> lst = new List<CultureModels>();

            foreach (var t in Item)
            {
                CultureModels model = new CultureModels();

                model.Condition_Find = t.Subject;
                model.CultureID = t.CultureID;
                model.GroupID = t.GroupID;
                if (t.GroupID == 13)
                {
                    model.GroupName = "Kỹ năng sống";
                }
                if (t.GroupID == 14)
                {
                    model.GroupName = "Truyện - thơ";
                }
                model.Subject = t.Subject;
                model.ImageContentUrl = t.ImageContentUrl;
                model.ShortcutText = t.ShortcutText;
                model.Contents = t.Contents;
                model.VisibleContent = t.VisibleContent;
                model.Locked = t.Locked;
                model.CreationDate = t.CreationDate;
                lst.Add(model);
            }

            return lst;
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ManageCulture(CultureModels model)
        {
            //if (ModelState.IsValid)
            if (ValidateNews(model))
            {
                TimeSpan ts = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

                CulturesAll Item = new CulturesAll();
                Item.CultureID = model.CultureID;
                Item.GroupID = model.GroupID;
                Item.Subject = model.Subject;
                if (model.ImageContentUrl.ToString().IndexOf("/") > 0)
                {
                    Item.ImageContentUrl = model.ImageContentUrl;
                }
                else
                {
                    Item.ImageContentUrl = ConfigurationManager.AppSettings["CulturePath"] + model.ImageContentUrl;// get default directory from web.config
                }
                Item.ShortcutText = model.ShortcutText;
                Item.Contents = model.Contents;
                Item.VisibleRight = true;
                Item.RightOrder = 1;
                Item.VisibleContent = model.VisibleContent;
                Item.ContentOrder = 1;
                Item.Locked = model.Locked;
                Item.CreationBy = AuthConfig.UserInfo.UserID;
                Item.CreationDate = model.CreationDate + ts;
                Item.LastUpdatedBy = AuthConfig.UserInfo.UserID;
                Item.LastUpdatedDate = DateTime.Now;

                try
                {
                    if (model.CultureID == null || model.CultureID.ToString() == "" || model.CultureID == 0)//insert
                    {
                        conn.CulturesAlls.AddObject(Item);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Thêm mới thành công!");
                    }
                    else //update
                    {

                        conn.CulturesAlls.Attach(Item);
                        conn.ObjectStateManager.ChangeObjectState(Item, EntityState.Modified);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Cập nhật thành công!");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", ValidateMessages.ErrorDescription(MembershipStatus.Error));
                }
            }

            ViewData["lstNewsGrp"] = GetListNewsGrp("");
            ViewData["lstNewsGrpSrch"] = GetListNewsGrp("SEARCH");
            return View(model);
        }

        private bool ValidateNews(CultureModels model)
        {
            if (model.Subject == null || model.Subject.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập tiêu đề!");
                return false;
            }
            if (model.ImageContentUrl == null || model.ImageContentUrl.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui chọn nhập hình đại diện!");
                return false;
            }
            if (model.ShortcutText == null || model.ShortcutText.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập tóm tắt nội dung!");
                return false;
            }
            if (model.Contents == null || model.Contents.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập nội dung tin!");
                return false;
            }
            if (model.CreationDate == null || model.CreationDate.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập ngày!");
                return false;
            }
            return true;
        }
        public ActionResult DeleteNews(string CultureID)
        {
            if (CultureID.ToString() != "" && CultureID != "0")
            {
                CulturesAll model = new CulturesAll();
                int strLabelID = int.Parse(CultureID);

                model = (CulturesAll)conn.CulturesAlls.Where(t => t.CultureID == strLabelID).SingleOrDefault();

                try
                {
                    conn.CulturesAlls.DeleteObject(model);
                    conn.SaveChanges();
                    ModelState.AddModelError("", "Xóa dữ liệu thành công!");
                    return Json("Xóa dữ liệu thành công", JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {

                    return Json("Xóa dữ liệu lỗi, vui lòng liên hệ quản trị hệ thống!", JsonRequestBehavior.AllowGet);
                }
            }
            //return RedirectToAction("DeleteNewsCatalogueSuccess");
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
    }
}
